<?php
namespace App\Http\Admin\Middleware;

use Closure;
use Dingo\Api\Http\Response;

class ProcessJsonResponse
{
    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if (env("APP_DEBUG")&&$response instanceof Response &&app()->bound('debugbar') &&app('debugbar')->isEnabled()) {
            
            $debugbar_data=app('debugbar')->getData();
            $queries_data = $this->sqlFilter($debugbar_data);
            $total_duration_time=array_get($debugbar_data, 'time.duration_str');
            $response->setContent(json_decode($response->morph()->getContent(), true) + [
                '_debugbar' => [
                    'total_queries' => count($queries_data),
                    'total_duration_time'=>$total_duration_time,
                    'queries' => $queries_data,
                ]
            ]);
        }

        return $response;
    }

    /**
    * Get only sql and each duration
    *
    * @param $debugbar_data
    * @return array
    */
    protected function sqlFilter($debugbar_data) {
        $result = array_get($debugbar_data, 'queries.statements');

        return array_map(function ($item) {
            return [
                'sql' => array_get($item, 'sql'),
                'duration' => array_get($item, 'duration_str'),
            ];
        }, $result);
    }
}